module MutMS(
	input				clk100M,
	input				rst_n,
	input		[15:0]	addr,			//地址
	input		[31:0]	data_w,			//FPGA2_FPGA1写数据
	output	reg	[31:0]	data_r,			//FPGA2_FPGA1读数据

	output				spi_cs,
	output				spi_clk,
	input				spi_miso,
	output				spi_mosi	//
);

reg[15:0] W_CMD;        /*读回来的地址*/
reg[15:0] R_CMD;        /*读回来的地址*/
wire [31:0]READ_DATA; /*读回来*/
reg rd_en;
reg tx_en;
reg en_all;
reg [31:0]W_DATA;  /*写下去*/
wire CS_R;
wire CS_W;
wire SPI_SCLK_R;
wire SPI_SCLK_W;
wire SPI_SDO_R;
wire SPI_SDO_W;
assign spi_cs	= en_all ? CS_R : CS_W;
assign spi_clk	= en_all ? SPI_SCLK_R : SPI_SCLK_W;
assign spi_mosi	= en_all ? SPI_SDO_R : SPI_SDO_W;
MutMiso master_r(
	.clk_in(clk100M),
	.rst_n(rst_n),
	.rd_en(rd_en),
	.CS(CS_R),
	.SPI_SCLK(SPI_SCLK_R),
	.SPI_SDI(spi_miso),
	.SPI_SDO(SPI_SDO_R),
	.CMD(R_CMD),			//不用读地址
	.DATA1(READ_DATA)	//读回来的1个32位数据
);

MutMosi master_w(
	.clk_in(clk100M),
	.rst_n(rst_n),
	.tx_en(tx_en),
	.CS(CS_W),
	.SPI_SCLK(SPI_SCLK_W),
	.SPI_SDO(SPI_SDO_W),
	.CMD(W_CMD),			//写向FPGA1的命令，即FPGA1的16位地址
	.DATA(W_DATA)	//待传输数据
);


always @(posedge clk100M or negedge rst_n) begin
	if (!rst_n) begin
		en_all	<= 1'b0;
		tx_en	<= 1'b0;
		rd_en	<= 1'b0;
		W_CMD	<= 16'h0;
		R_CMD	<= 16'h0;
		W_DATA	<= 32'h0;
	end else begin
		case (addr)
			16'h1001: begin
				en_all	<= 1'b0;
				tx_en	<= 1'b0;
				W_CMD	<= data_w[15:0];
			end
			16'h1002: begin
				tx_en	<= 1'b1;
				W_DATA	<= data_w;
			end
			16'h0001: begin
				en_all	<= 1'b1;
				rd_en	<= 1'b1;
				R_CMD	<= data_w[15:0];
			end
			16'h0002: begin
				rd_en	<= 1'b0;
			end
			default: begin
				en_all	<= 1'b0;
				tx_en	<= 1'b0;
				rd_en	<= 1'b0;
				W_CMD	<= W_CMD;
				R_CMD	<= R_CMD;
				W_DATA	<= W_DATA;
			end
		endcase
	end
end

always @(posedge clk100M or negedge rst_n) begin
	if (!rst_n) begin
		data_r	<= 32'h0;
	end else begin
		data_r	<= READ_DATA;
	end
end



endmodule

